package jwt4_token

import (
	"github.com/dgrijalva/jwt-go/v4"
	"time"
)

// go get github.com/dgrijalva/jwt-go/v4
// jwt解析网站：https://jwt.io/
type JwtPayLoad struct {
	NickName string `json:"nickName"`
	RoleID   uint   `json:"roleID"`
	UserID   uint   `json:"userID"`
}

// 密钥
var Secret = []byte("waiwaihu")

type CustomCliams struct {
	JwtPayLoad
	jwt.StandardClaims
}

// 生成Token
func GerenceToken(j JwtPayLoad) (string, error) {
	climas := CustomCliams{
		JwtPayLoad: j,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: jwt.At(time.Now().Add(24 * time.Hour)), //过期时间
			IssuedAt:  jwt.At(time.Now()),                     //生成时间
			Issuer:    "waiwaihu",                             //作者
			Subject:   "Token",                                //主题
		},
	}
	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, climas).SignedString(Secret)
	return token, err
}

// 解析token
func ParseToken(token string) (*CustomCliams, error) {
	Token, err := jwt.ParseWithClaims(token, &CustomCliams{}, func(token *jwt.Token) (interface{}, error) {
		return Secret, nil
	})
	//fmt.Println(Token.Claims)

	if err != nil {
		return nil, err
	}
	clamis, ok := Token.Claims.(*CustomCliams)
	// 判断令牌是否无效
	if !ok || !Token.Valid {
		return nil, err
	}
	return clamis, nil
}
